<template>
    <!-- form 查询表单 -->
    <el-form :model="order" ref="formRef" label-width="auto" label-position="right" style="padding-bottom: 10px;">
        <el-row :gutter="20">
            <el-col :span="5">
                <el-form-item label="订单编号" prop="dingdan_num">
                    <el-input v-model="order.dingdan_num" placeholder="请输入订单编号" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item label="用户名" prop="user_id">
                    <el-input v-model="order.name" placeholder="请输入用户名" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item label="状态" prop="state">
                    <el-select v-model="order.state" placeholder="状态" clearable>
                        <!--
                        * 订单状态
                        * 0：待接单
                        * 1：商家未接单
                        * 2：商家已接单
                        * 3：骑手已接单
                        * 4：配送中
                        * 5：订单完成
                        -->
                        <el-option label="全部" value="" />
                        <el-option label="待接单" value="0" />
                        <el-option label="商家未接单" value="1" />
                        <el-option label="商家已接单" value="2" />
                        <el-option label="骑手已接单" value="3" />
                        <el-option label="配送中" value="4" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-button type="primary" @click="doList">查询</el-button>
                <el-button type="default" @click="resetForm(formRef)">重置</el-button>
            </el-col>
        </el-row>
    </el-form>

    <!-- table 表格 -->
    <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" sortable/>
        <el-table-column prop="dingdan_num" label="订单编号" sortable/>
        <el-table-column prop="shop_name" label="商家名"/>
        <el-table-column prop="name" label="用户名"/>
        <el-table-column prop="phone" label="手机号"/>
        <el-table-column prop="state" label="状态" >
            <template #default="scope">
                <el-tag v-if="scope.row.state === '0'" type="info">待接单</el-tag>
                <el-tag v-else-if="scope.row.state === '1'" type="info">商家未接单</el-tag>
                <el-tag v-else-if="scope.row.state === '2'" type="warning">商家已接单</el-tag>
                <el-tag v-else-if="scope.row.state === '3'" type="warning">骑手已接单</el-tag>
                <el-tag v-else-if="scope.row.state === '4'" type="primary">配送中</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
            <template #default="scope">
                <el-button type="primary" @click="showOrderDetail(scope.row)">详情</el-button>
                <el-button v-if="['0', '1'].includes(scope.row.state)" type="info" disabled>待商家接单</el-button>
                <el-button v-else-if="scope.row.state === '2'" type="warning" @click="acceptOrder(scope.row)">接单</el-button>
                <el-button v-else-if="scope.row.state === '3'" type="warning" @click="startDelivery(scope.row)">开始配送</el-button>
                <el-button v-else-if="scope.row.state === '4'" type="success" @click="markAsDelivered(scope.row)">已送达</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container" style="margin-top: 20px;">
        <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 50]"
            v-model:current-page="page.pageNum"
            v-model:page-size="page.pageSize"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <!-- 详情 页面 -->
    <order-detail-page ref="orderDetailPageRef" />
</template>

<script setup lang="ts">
import axios from 'axios'
import {ref, onMounted} from 'vue'
import {ElMessage, FormInstance} from "element-plus";
import OrderDetailPage from './OrderDetailPage.vue'

// form 查询表单绑定的数据对象：order
const order = ref({
    dingdan_num: '',
    name: '',
    state: '',
})

// table 数据表格绑定的数据对象：tableData
const tableData = ref([])

// 分页相关变量
const page = ref({
    pageNum: 1,     // 当前页码
    pageSize: 20,    // 每页显示的记录数
    pages: 0,       // 总页数
    total: 0        // 总记录数
});

// 分页事件处理
const handleSizeChange = (val: number) => {
    page.value.pageSize = val;
    page.value.pageNum = 1;
    doList();
};

const handleCurrentChange = (val: number) => {
    page.value.pageNum = val;
    doList();
};

// 查询
const doList = async () => {
    try {
        // 构建查询参数，只传递有值的参数
        const params: any = {
            pageNum: page.value.pageNum,
            pageSize: page.value.pageSize
        };

        // 只添加非空的查询条件
        if (order.value.dingdan_num && order.value.dingdan_num.trim() !== '') {
            params.dingdan_num = order.value.dingdan_num.trim();
        }

        if (order.value.name && order.value.name.trim() !== '') {
            params.name = order.value.name.trim();
        }

        if (order.value.state !== '') {
            params.state = order.value.state;
        }

        const { data } = await axios.get('/api/dingdan', { params })

        console.log('接口返回的 data:', data)

        // 处理分页数据
        if (data && Array.isArray(data.list)) {
            // 过滤掉状态为5的订单
            tableData.value = data.list.filter(item => item.state !== '5');
            page.value.total = data.total || 0;
            page.value.pages = data.pages || 0;
        } else if (data && data.data && Array.isArray(data.data.list)) {
            // 处理嵌套分页数据格式
            tableData.value = data.data.list.filter(item => item.state !== '5');
            page.value.total = data.data.total || 0;
            page.value.pages = data.data.pages || 0;
        } else {
            ElMessage.warning('订单数据格式不正确')
            tableData.value = []
            page.value.total = 0;
            page.value.pages = 0;
        }

    } catch (error) {
        console.error('请求订单列表失败:', error)
        ElMessage.error('获取订单数据失败: ' + (error.response?.data?.message || error.message))
        tableData.value = []
        page.value.total = 0;
        page.value.pages = 0;
    }
}

// 重置表单
const resetForm = (formEl: FormInstance) => {
    if (!formEl) return
    formEl.resetFields()
    // 重置分页参数
    page.value.pageNum = 1;
    page.value.pageSize = 5;
    doList() // 重置后重新查询
}

// 初始化
onMounted(() => {
    doList()
})

const formRef = ref<FormInstance>();

// 查看详情
const detailPageRef = ref()
const showDetailPage = (obj) => {
    detailPageRef.value.handleDetailData(obj)
}

// 获取当前骑手ID
const currentRiderId = localStorage.getItem('riderId') || sessionStorage.getItem('riderId');

// 接单
const acceptOrder = async (row) => {
    try {
        // 在接单时，同时设置 rider_id 为当前骑手ID
        await axios.put('/api/dingdan', {
            ...row,
            state: '3',
            rider_id: currentRiderId
        });
        ElMessage.success('接单成功');
        doList(); // 刷新表格数据
    } catch (error) {
        ElMessage.error('接单失败: ' + (error.response?.data?.message || error.message));
    }
}

// 开始配送：状态由 3 改为 4
const startDelivery = async (row) => {
    try {
        await axios.put('/api/dingdan', { ...row, state: '4' })
        ElMessage.success('配送已开始')
        doList() // 刷新表格数据
    } catch (error) {
        ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
    }
}

// 格式化时间为 YYYY-MM-DD HH:mm:ss
function formatTime(date: Date): string {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    const s = String(date.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
}

// 标记为已送达
const markAsDelivered = async (row) => {
    try {
        const now = formatTime(new Date());
        await axios.put('/api/dingdan', {
            ...row,
            state: '5',
            end_time: now
        });
        ElMessage.success('订单已标记为已送达');
        doList(); // 刷新表格数据
    } catch (error) {
        ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
    }
}

const orderDetailPageRef = ref()
const showOrderDetail = (row) => {
    orderDetailPageRef.value.handleDetailData(row)
}
</script>


<style scoped>
.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>
